<template>
  <div class="dc-container">
    <el-dialog v-model="visible" width="50%"
      :fullscreen="false" :title="title" :close-on-click-modal="false"
      @open="onDialogOpen" @close="onDialogClose">
      <el-form ref="editForm" :model="form" :rules="rules" label-width="100px" :disabled="mode == 'view'">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="company.id" label="公司">
              <el-cascader v-model="form.company.id" :options="companyOptions"
                separator="/" placeholder="请选择公司" clearable filterable
                :props="{ label: 'name', value: 'id', children: 'children', checkStrictly: true, emitPath: false }"
                :style="{ width: '100%' }"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="parent.id" label="父级部门">
              <el-cascader v-model="form.parent.id" :options="departmentOptions"
                separator="/" placeholder="请选择父级部门" clearable filterable
                :props="{ label: 'name', value: 'id', children: 'children', checkStrictly: true, emitPath: false }"
                :style="{ width: '100%' }"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="code" label="编号">
              <el-input v-model="form.code" :maxLength="64" placeholder="请输入编号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="name" label="名称">
              <el-input v-model="form.name" :maxLength="128" placeholder="请输入名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="director.id" label="总监">
              <el-select v-model="form.director.id" placeholder="请选择总监" clearable filterable style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="manager.id" label="经理">
              <el-select v-model="form.manager.id" placeholder="请选择经理" clearable filterable style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="remarks" label="备注信息">
              <el-input v-model="form.remarks" type="textarea" :rows="3" :maxLength="255" placeholder="请输入备注信息" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onSubmit" type="primary" v-show="mode != 'view'">保存</el-button>
          <el-button @click="onDialogClose" v-if="mode != 'view'">取消</el-button>
          <el-button @click="onDialogClose" v-if="mode == 'view'">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getDepartmentById, saveDepartment, treeDepartment } from '@/api/org/department'
import BaseUI from '@/views/components/baseUI'
import OperationIcon from '@/components/OperationIcon'

import { treeCompany } from '@/api/org/company'
import { listUserAll } from '@/api/sys/user'

export default {
  extends: BaseUI,
  name: 'department-form',
  components: {
    OperationIcon
  },
  data() {
    return {
      mode: 'add',
      form: this.initForm(),
      visible: false,
      title: '部门',
      rules: {
        'company.id': [{ required: true, message: '公司不能为空', trigger: 'blur' }],
        'code': [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        'name': [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },

      companyOptions: [],
      departmentOptions: [],
      userOptions: []
    }
  },
  props: {
    permission: {
      type: Object
    }
  },
  methods: {
    onSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.doSave()
        } else {
          return false
        }
      })
    },
    doSave() {
      this.setLoad()
      saveDepartment(this.form)
        .then((responseData) => {
          if (responseData.code == 100) {
            this.visible = false
            this.showMessage({
              type: 'success',
              msg: '保存成功'
            })
            this.$emit('save-finished')
          } else {
            this.showMessage(responseData)
          }
          this.resetLoad()
        })
        .catch((error) => {
          this.outputError(error)
        })
    },
    getFormById(id) {
      this.setLoad()
      return new Promise((resolve) => {
        getDepartmentById(id)
          .then((responseData) => {
            let form = {}
            if (responseData.code == 100) {
              form = responseData.data
            } else {
              this.showMessage(responseData)
            }
            this.resetLoad()
            resolve(form)
          })
          .catch((error) => {
            this.outputError(error)
          })
      })
    },
    onDialogClose() {
      this.visible = false
    },
    onDialogOpen() {
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
    },
    initForm() {
      return {
        id: null,
        company: {id: null},
        parent: {id: null},
        code: '',
        name: '',
        sort: 0,
        director: {id: null},
        manager: {id: null},
        remarks: ''
      }
    },
    async openView(id) {
      this.mode = 'view'
      this.title = `查看部门`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions()
      this.visible = true
    },
    async openEdit(id) {
      this.mode = 'edit'
      this.title = `修改部门`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions()
      this.visible = true
    },
    openAdd(parent) {
      this.mode = 'add'
      this.title = `添加部门`
      this.form = this.initForm()
      if(parent) {
        this.form.parent.id = parent.id
        if(parent.company && parent.company.id) {
          this.form.company.id = parent.company.id
        }
      }
      this.initOptions()
      this.visible = true
    },
    async openCopy(id) {
      this.mode = 'add'
      this.title = `添加部门`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions()
      this.form.id = null
      this.visible = true
    },

    initCompanyOptions() {
      let search_List = {
        params: []
      }

      treeCompany(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.companyOptions = responseData.data
        } else {
          this.showMessage(responseData)
        }
      })
    },
    
    initDepartmentOptions() {
      if (!this.form.company || !this.form.company.id) return
      
      const params = [{
        columnName: 'department.company_id',
        queryType: '=',
        value: this.form.company.id
      }]
      
      treeDepartment({params: params}).then(response => {
        if (response.code == 100) {
          this.departmentOptions = response.data
        } else {
          this.showMessage(response)
        }
      })
    },
    
    initUserOptions() {
      let search_List = {
        params: []
      }
      
      if (this.form.company && this.form.company.id) {
        search_List.params.push({
          columnName: 'user.company_id',
          queryType: '=',
          value: this.form.company.id
        })
      }

      listUserAll(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.userOptions = responseData.data
        } else {
          this.showMessage(responseData)
        }
      })
    },
    
    initOptions() {
      // 1. 先初始化基础数据（不依赖其他数据的选项）
      this.initCompanyOptions()
      
      // 2. 再初始化一级依赖数据
      if (this.form.company && this.form.company.id) {
        this.initDepartmentOptions()
        this.initUserOptions()
      }
    }
  },
  watch: {
    'form.company.id': {
      handler(newVal) {
        // 重新加载部门数据
        this.initDepartmentOptions()
        // 重新加载用户数据
        this.initUserOptions()
        // 清空已选部门
        this.form.parent.id = null
        // 清空已选用户
        this.form.director.id = null
        this.form.manager.id = null
      }
    }
  }
}
</script> 